const mongoose = require('mongoose')
const logger = require('./log4js').api

const connect = () => {
  mongoose.connect(process.env.MONGO_ADDR, { keepAlive: 120, useNewUrlParser: true, useUnifiedTopology: true })
}
connect()
const db = mongoose.connection

db.once('open', () => {
  logger.info('Connecting to the database Successfully')
})

db.on('error', function (error) {
  logger.error('Error in MongoDb connection: ' + error)
  mongoose.disconnect()
})

db.on('close', function () {
  logger.info('The database is disconnected and try to reconnect the database')
  connect()
})

module.exports = db
